<template>
  <div class="padding_10">
    <div>
      <el-button
        v-permissions="{ permission: ['add:GoodsList'] }"
        type="primary"
        @click="back"
      >
        发布商品
      </el-button>
    </div>
    <div style="margin-top: 10px">
      <!-- 筛选输入，选择 -->
      <div class="grid_4_column" style="margin: 10px 0">
        <div>
          商品名称：
          <el-input
            v-model="goods_name"
            clearable
            maxlength="50"
            placeholder="输入商品名称"
            style="width: 200px"
            type="text"
          />
        </div>
        <div>
          商品条码：
          <el-input
            v-model="goods_code"
            clearable
            maxlength="50"
            placeholder="请输入商品条码"
            style="width: 200px"
            type="text"
          />
        </div>
        <div>
          商品类型：
          <el-select v-model="method_id" clearable placeholder="请选择商品类型">
            <el-option
              v-for="(item, index) of typeOptions"
              :key="index"
              :label="item.method_name"
              :value="item.id"
            />
          </el-select>
        </div>
      </div>

      <!-- 筛选，导出按钮 -->
      <div>
        <el-button
          icon="el-icon-search"
          :loading="filterLoading"
          type="primary"
          @click="getGoods('filterLoading')"
        >
          筛选
        </el-button>
        <el-button
          icon="el-icon-refresh"
          :loading="exportLoading"
          @click="exportTableData"
        >
          重置
        </el-button>
      </div>
    </div>

    <!-- 标签页 -->
    <el-tabs
      v-model="activeName"
      style="margin-top: 10px"
      type="card"
      @tab-click="clcikTab"
    >
      <el-tab-pane
        v-for="items of commodityLabel"
        :key="items"
        :label="items"
        :name="items"
      >
        <!-- 表格功能按钮 -->
        <div class="flex_y_center demo">
          <el-button class="func_btn" @click="takeDown">下架</el-button>
        </div>

        <!-- elements表格 -->
        <el-table
          :data="tableData"
          :empty-text="emptyText"
          style="width: 100%; margin-top: 15px"
          @selection-change="handleSelectionChange"
        >
          <!-- 全选表头 -->
          <el-table-column type="selection" />
          <!-- 自定义表头 -->
          <el-table-column label="商品名称" show-overflow-tooltip>
            <template slot-scope="scope">
              <div>{{ scope.row.goods_name }}</div>
              <el-tag size="mini">{{ scope.row.goods_type_name }}</el-tag>
            </template>
          </el-table-column>
          <!-- 固定表头 -->
          <el-table-column label="商品分组" prop="goods_method_name" sortable />
          <el-table-column label="商品价格" prop="goods_price" sortable />
          <el-table-column label="商品编码" prop="goods_sn" sortable />
          <el-table-column
            label="发货方式"
            prop="delivery_method_name"
            sortable
          />
          <el-table-column label="创建时间" prop="created_at" sortable />
          <el-table-column label="商品状态" prop="status" sortable />
          <!-- 自定义表头 -->
          <el-table-column align="left" label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                v-permissions="{ permission: ['edit:GoodsList'] }"
                type="primary"
                @click="editProduct('编辑', scope.$index, scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.goods_status == 'on'"
                v-permissions="{ permission: ['offline:GoodsList'] }"
                @click="editProduct('下架', scope.$index, scope.row)"
              >
                下架
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 分页 -->
    <div class="flex_between">
      <div></div>
      <el-pagination
        :current-page.sync="page"
        layout="prev, pager, next, jumper"
        :total="total"
        @current-change="getGoods"
      />
    </div>
  </div>
</template>

<script>
  import { getGoodsList, setUpDownStatus } from '@/api/commodity'
  import { getCommodityType } from '@/api/commodityType'

  export default {
    data() {
      return {
        emptyText: ' ',
        tableData: [], // 存放后端获取到的商品列表信息
        page: 1, // 用作请求商品列表时的分页参数
        total: 10, // 控制分页显示的页码数

        typeOptions: [],
        // 筛选信息存储
        method_id: '', // 商品类型
        goods_name: '', // 商品名称
        goods_code: '', // 商品编号
        filterLoading: false, // 控制筛选按钮加载样式
        exportLoading: false, /// 控制导出按钮加载样式

        // 商品标签页
        commodityLabel: ['全部', '销售中', '仓库'],
        activeName: '全部',
        commodityIdArr: [], // 存放批量选中商品id，上下架状态
      }
    },
    computed: {
      goodsStatus() {
        if (this.activeName == '销售中') {
          return 'on'
        } else if (this.activeName == '仓库') {
          return 'off'
        } else {
          return ''
        }
      },
    },
    mounted() {
      this.getGoods()
      this.getGoodsType()
    },
    methods: {
      // 切换标签页
      clcikTab(e) {
        this.activeName = e.label
        this.getGoods()
      },
      // 获取商品信息列表
      getGoods(btnLoading) {
        this[btnLoading] = true
        const loading = this.$loading({
          lock: true,
          target:
            this.tableData.length == 0
              ? '.el-table__empty-block'
              : '.el-table__body',
        })
        const params = {
          page: this.page,
          goods_status: this.goodsStatus,
          goods_name: this.goods_name,
          goods_code: this.goods_code,
          method_id: this.method_id,
          pagesize: 10,
        }
        // 获取商品列表
        getGoodsList(params).then((res) => {
          this.tableData = res.data.list.data
          for (let item of this.tableData) {
            item.goods_status == 'on'
              ? (item.status = '销售中')
              : (item.status = '仓库')
          }
          this.total = res.data.list.last_page * 10
          this[btnLoading] = false
          loading.close()
          if (res.data.list.data.length == 0) {
            this.emptyText = '暂无数据'
          }
        })
      },
      // 获取商品类型
      getGoodsType() {
        getCommodityType().then((res) => {
          this.typeOptions = res.data.data
        })
      },
      // 重置已获取的数据
      exportTableData() {
        this.method_id = ''
        this.goods_name = ''
        this.goods_code = ''
        this.getGoods('exportLoading')
      },
      // 批量下架
      takeDown() {
        this.$confirm('确定要对选中的商品下架吗', '下架', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          // 点击确认执行
          if (this.commodityIdArr.length == 0) {
            this.$message.warning('请先选择商品在执行此操作')
          } else {
            const params = {
              id: JSON.stringify(this.commodityIdArr),
              goods_status: 'off',
            }
            // 调用修改上下架状态接口函数
            setUpDownStatus(params).then(() => {
              this.$message.success('所选商品下架成功')
              // 调用该函数，重新获取商品列表信息进行渲染
              this.getGoods()
            })
          }
        })
      },
      // 批量添加商品上下架状态
      handleSelectionChange(selectionArr) {
        this.commodityIdArr = []
        for (let item of selectionArr) {
          this.commodityIdArr.push(item.id)
        }
      },
      // 编辑商品
      editProduct(btnName, a, commObj) {
        if (btnName == '编辑') {
          this.$emit('send', commObj.id)
        } else if (btnName == '下架') {
          this.$confirm(
            '确定要将' + commObj.goods_name + '商品下架码？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(() => {
            const params = {
              id: commObj.id,
              goods_status: commObj.goods_status == 'on' ? 'off' : 'on',
            }
            setUpDownStatus(params).then(() => {
              this.$message.success('商品' + commObj.goods_name + '已下架')
              this.getGoods()
            })
          })
        } else {
          this.$message.error('暂不支持' + btnName + '功能')
        }
      },
      back() {
        this.$emit('send', 0)
      },
    },
  }
</script>

<style scoped>
  .grid_4_column {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 10px;
  }
  .flex_between {
    display: flex;
    justify-content: space-between;
  }
</style>
